﻿using System;
using System.Data.Entity;
using MvcDesign.Core.CoreDataModel;

namespace MvcDesign.Core.DataAccess
{
    public class DataContext : IDisposable
    {
        private class DomainModelContext : DbContext
        {
            private readonly DataContext _parent;

            public DomainModelContext(DataContext parent, string connection) : base(connection)
            {
                _parent = parent;
            }

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                _parent.OnModelCreating();
            }
        }

        private readonly DbContext _context;

        public DataContext()
        {
            _context = new DomainModelContext(this, "Data");
        }

        public ObjectCollection<T> GetCollection<T>() where T: class, IDataObject
        {
            return new ObjectCollection<T>(_context.Set<T>());
        }

        public int SaveChanges()
        {
            return _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }

        void OnModelCreating()
        {
            DataInitializer.Initialize(this);
        }
    }
}
